package br.com.amigooo.controller;


import static br.com.caelum.vraptor.view.Results.json;

import java.util.List;

import br.com.amigooo.Session.UserSession;
import br.com.amigooo.model.Establishment;
import br.com.amigooo.model.EstablishmentList;
import br.com.amigooo.model.ReturnMessage;
import br.com.amigooo.repository.EstablishmentImpl;
import br.com.amigooo.util.Utils;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

@Resource
public class CompanyController {

	private Result result;
	private UserSession userSession;
	private Establishment establishment;

	public CompanyController(Result result, UserSession userSession) {
		this.result = result;
		this.userSession = userSession;
		
	}

	public void start() {
	}

	@Path("/company")
	public void index() {
		EstablishmentImpl establishmentImpl = new EstablishmentImpl();

		if (userSession != null) {
			this.establishment = establishmentImpl.getEstablishment(userSession
					.getUser().getEstablishment().getId());
			
			result.include("establishment", this.establishment);
		}
	}
	
	@Post
	@Path("/company/save")
	public void save(Establishment establishment) {
		if(establishment != null) {
			if(establishment.getId() != null) {
				EstablishmentImpl establishmentImpl = new EstablishmentImpl();
				establishment.setUser(establishmentImpl.getEstablishment(establishment.getId()).getUser());
				
				try{
					establishmentImpl.update(establishment);
			
					result.include("result", Utils.message("As informações foram atualizadas!", Utils.SUCCESS)).redirectTo(this).index();
				}catch (RuntimeException e){
					e.printStackTrace();
					
					result.include("result", Utils.message("Ocorreu um erro ao tentar salvar as alterações.", Utils.ERROR)).redirectTo(this).index();
				}
			}
		}
	}
	
	@Get
	@Path("/mobile/establishment/{name}")
	public void searchEstablishment(String name){
		EstablishmentList establishmentList = new EstablishmentList();
		List<Establishment> establishment = null;
		EstablishmentImpl establishmentImpl = new EstablishmentImpl();
		
		if(name != null && !"".equals(name.trim())){
			establishment = establishmentImpl.getEstablishmentListByName(name);
		}
		
		if(establishment != null && !establishment.isEmpty()){
			establishmentList.setEstablishments(establishment);
			result.use(json()).from(establishment).serialize();
		}else{
			result.use(json()).from(new ReturnMessage("Não encontrado", "5", null)).serialize();
		}
	}
}
